<!--
 * @name score
 * @description 组件描述
 * @author idouya
 * @email elegentfrog@163.com
 * @date 2025-07-03
 -->

<template>
  <div class="p-score common-bg common-layout">
    <page-title
      :discipline="gameInfo.discipline"
      :event="gameInfo.event"
      :match="gameInfo.match"
      :type="gameInfo.type"
      :eventName="gameInfo.eventName"
      :startTime="gameInfo.startTime"
      :showTime="true"
    ></page-title>
    <div class="content">
      <div class="content-top">
        <div class="line1">
          <div class="order">{{ atheleteInfo.Order }}</div>
          <div class="name">{{ atheleteInfo.AthleteName }}</div>
          <div class="club">{{ atheleteInfo.CountryName }}</div>
          <div class="time">
            {{ formattedTime }}
          </div>
        </div>
        <div class="line1">
          <div class="order horseOrder">{{ atheleteInfo.HorseOrder }}</div>
          <div
            class="name horseName"
            :class="[atheleteInfo?.HorseName?.length > 12 ? 'horseNameAdapt' : '']"
          >
            {{ atheleteInfo.HorseName }}
          </div>
          <div class="line1-time">
            <div
              class="posture"
              :style="
                posture.length > 8
                  ? posture.length > 15
                    ? 'font-size: 3.9rem'
                    : 'font-size: 4.1rem'
                  : ''
              "
            >
              {{ posture }}
            </div>
          </div>
        </div>
      </div>
      <div class="content-bottom" v-if="temShowRank">
        <div class="bottom-item" v-for="(item, index) in rankData" :key="index">
          <div class="item-left">{{ item?.Rank }}</div>
          <div class="item-right">
            <div class="right-content">
              <div class="delegation">{{ item?.CountryName }}</div>
              <div class="name">{{ item?.AthleteName }}</div>
              <div
                class="horseName"
                :class="[atheleteInfo?.HorseName?.length > 13 ? 'horseNameAdapt' : '']"
              >
                {{ item?.HorseName }}
              </div>
              <div class="percentage">{{ item?.Score }}</div>
              <!-- <div class="score">
                <template v-for="(judge, num) in judgeList" :key="num">
                  <div class="scoreE" v-if="item[judge.col]">
                    {{ judge.col }}:{{ item[judge.col] }}
                  </div>
                </template>
              </div> -->
            </div>
            <img src="@/assets/img/scb/line-divide.png" alt="" height="2px" width="100%" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useStore from '@/store'
import Storage from '@/assets/js/storage'
import Utils from '@/assets/js/utils'
import Config from '@/assets/js/config'
import { useMultiProcRequest } from '@/assets/js/useMultiProcRequest'
import { computed } from 'vue'

const { results, fetchForProcs } = useMultiProcRequest()
const status = ref(-1)

const gameInfo = ref({
  discipline: '马术',
  match: '',
  eventName: '',
  event: 'DRESINDV',
  // type: '实时成绩',
  startTime: '13:01:29',
})

const atheleteInfo = ref({
  order: 1,
  name: '杨舒涵',
  delegation: '中国',
  horseOrder: 201,
  club: '好骑士嘉豪马术',
  horseName: 'Joanna',
  time: '00:00',
})

const process = ref([{ name: '立定敬礼', order: 1 }])

const rankData = ref([])

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const params = ref({})
const procName = ref([])
const commonStore = useStore.useCommonStore()
const baseRunTime = ref(0)
const hasStartedOnce = ref(false)
const postFlag = ref(null)

const runTime = ref(-1)
const time0 = ref(0)
const time1 = ref(0)
const isRunning = ref(false)
const showAction = ref(0)
const playAction = ref(null)
const temShowRank = ref(false)
const judgeList = ref([])

let timer1 = null

onBeforeMount(() => {
  clearInterval(timer1)
})

onMounted(async () => {
  params.value = route.query
  procName.value = Config.procNameList[route.name]
  init()
})

const init = async () => {
  params.value = route.query
  procName.value = Config.procNameList[route.name]
  await getData()
  // const lastMsg = commonStore.receivedActionMessages?.slice(-1)[0]
  // if (lastMsg && lastMsg.tplCode == 'scb-dressage-score5') {
  //   handleMessage(lastMsg)
  // }
  startTimer()
}

const posture = computed(() => {
  if (atheleteInfo.value?.Posture && showAction.value) {
    return atheleteInfo.value?.Posture
  }
  return ''
})

// 计算格式化时间（00:00）
const formattedTime = computed(() => {
  if (runTime.value == -1) return
  else if (runTime.value == 0) return '00:00'
  const min = Math.floor(runTime.value / 60)
    .toString()
    .padStart(2, '0')
  const sec = (runTime.value % 60).toString().padStart(2, '0')
  return `${min}:${sec}`
})

// 运行时间计时器
const startTimer = () => {
  timer1 = setInterval(() => {
    if (isRunning.value) {
      runTime.value += 1
    }
  }, 1000)
}

const getData = async () => {
  if (procName.value.length > 0) {
    await fetchForProcs(procName.value, {
      procName: procName.value[0],
      keyValues: params.value,
    })
  }
}

const handleMessage = async (msg) => {
  temShowRank.value = false
  const data = msg?.data
  postFlag.value = null
  if (data?.showAction == 1) {
    // await getData()
    showAction.value = data?.showAction
  }
  if (data?.playAction == 'in') {
    showAction.value = 0
    runTime.value = -1
  }
  if (data?.status == 1) {
    isRunning.value = true
  } else if (data?.status == 0) {
    isRunning.value = false
    runTime.value = 0
  } else if (data?.status == 3) {
    isRunning.value = false
  }
  if (Object.keys(data).length == 0) {
    showAction.value = 0
    runTime.value = -1
    clearInterval(timer1)
    temShowRank.value = true
  }
}

watchEffect(() => {
  if (results.value?.datasetList) {
    gameInfo.value.event = results.value.datasetList[0][0]?.EventCode
    gameInfo.value.match = results.value.datasetList[0][0].MatchName
    gameInfo.value.eventName = results.value.datasetList[0][0].EventName
    // const posture = atheleteInfo.value?.Posture
    // if (playAction.value == 'end') {
    //   atheleteInfo.value = {
    //     ...results.value.datasetList[0][0],
    //     Posture: posture,
    //   }
    // } else {
    // }
    atheleteInfo.value = results.value.datasetList[0][0]
    rankData.value = results.value.datasetList[1].slice(0, 6) || []
    judgeList.value = results.value.datasetList[2]
  }
})

watch(
  () => route.query,
  async (val) => {
    params.value = val
    // atheleteInfo.value.Posture = ''
    await getData()
  },
  { immediate: true }
)

watch(
  () => commonStore.receivedActionMessages,
  (newVal, oldVal) => {
    if (newVal.length > 0) {
      const latestMsg = newVal[newVal.length - 1]
      // playAction.value = latestMsg.data.playAction
      handleMessage(latestMsg)
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@import '@/assets/scss/dressage/score5';
</style>
